package cn.wsalix.weixin.entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.FetchType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

@Entity
@DynamicInsert
@DynamicUpdate
@Table(name = "WX_NEWS")
@Inheritance(strategy = InheritanceType.JOINED)
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@EntityListeners({ AuditingEntityListener.class })
public class NewsMsg extends BaseMsg {

    /**
	 * 
	 */
	private static final long serialVersionUID = 8897640338337467899L;
	private static final int WX_MAX_SIZE = 10;
    private              int maxSize     = WX_MAX_SIZE;
    @OneToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY, mappedBy = "newsMsg")
    private List<WxArticle> articles;

    public NewsMsg() {
        this.articles = new ArrayList<WxArticle>(maxSize);
    }

    public NewsMsg(int maxSize) {
        setMaxSize(maxSize);
        this.articles = new ArrayList<WxArticle>(maxSize);
    }

    public NewsMsg(List<WxArticle> articles) {
        setArticles(articles);
    }

    public int getMaxSize() {
        return maxSize;
    }

    public void setMaxSize(int maxSize) {
        if (maxSize < WX_MAX_SIZE && maxSize >= 1) {
            this.maxSize = maxSize;
        }
        if (articles != null && articles.size() > this.maxSize) {
            articles = articles.subList(0, this.maxSize);
        }
    }

    public List<WxArticle> getArticles() {
        return articles;
    }

    public void setArticles(List<WxArticle> articles) {
        if (articles.size() > this.maxSize) {
            this.articles = articles.subList(0, this.maxSize);
        } else {
            this.articles = articles;
        }
    }

    public void add(String title) {
        add(title, null, null, null);
    }

    public void add(String title, String url) {
        add(title, null, null, url);
    }

    public void add(String title, String picUrl, String url) {
        add(new WxArticle(title, null, picUrl, url));
    }

    public void add(String title, String description, String picUrl, String url) {
        add(new WxArticle(title, description, picUrl, url));
    }

    public void add(WxArticle article) {
        if (this.articles.size() < maxSize) {
            this.articles.add(article);
        }
    }


}
